package com.example.cxz2021606127.util;

import android.app.Activity;
import android.app.Application;

import java.util.ArrayList;

/**
 * 该类用于存储每一个Activity并实现完全退出整个App,即退出所有的Activity
 */
public class ExitActivityUtil extends Application {
    private ArrayList<Activity> activities = null;  //Activity 容器
    private static ExitActivityUtil instance;

    private ExitActivityUtil() {
        activities = new ArrayList<Activity>();
    }

    /**
     * 单例模式中获取唯一的ExitActivityUtil实例
     */
    public static ExitActivityUtil getInstance() {
        if (null == instance) {
            instance = new ExitActivityUtil();
        }
        return instance;
    }

    // 添加Activity到容器中
    public void addActivity(Activity activity) {
        if (activities != null && activities.size() > 0) {
            if (!activities.contains(activity)) {
                activities.add(activity);
            }
        } else {
            activities.add(activity);
        }
    }

    // 遍历所有Activity并finish
    public void exitAllActivity() {
        if (activities != null && activities.size() > 0) {
            for (Activity activity:activities) {
                activity.finish();
            }
        }
        System.exit(0);
    }

}
